18. Debugging CSS Solution

intro

As I said earlier, I came across this problem on accident. I'm presenting the solution in an order that's efficient and effective for your understanding, but I want you to know that this is the end product of a lot of experimentation. I spent quite a bit of time in developer tools playing with CSS properties, predicting what would happen before I made a change and then drawing conclusions after. I'm not alone in my approach. Here's a quote from Warren Ouyang, our lead front-end engineer, to whom I gave this problem. After he finished it, he said,

I would love to say I just looked at the code and figured it out, but I also did a bunch of playing around with it to understand it.

Here we go!


Remember, the shift from position: relative happens after the normal flow finishes. Let's start with the normal flow. Ignore position: relative for now.

Unchecking position: relative gives you this:

CSS Debugging

INSTRUCTOR NOTE:

Notice that the layout of two non-relative siblings stays the same!

Here is your smoking gun. Look at how the text lines up. You've seen this before.

smoking gun

Without relative positioning, the text lines up!

Without relative positioning, the text lines up!

agsasdfasdf

The sibling is an inline box and the "Child" text inside it is its text. As you learned a few pages ago, text will line up with the baseline of a parent. The baseline of the parent is lowered by the extra text inside the relative sibling. As a result, the text of the other siblings is lowered.

Now, realize that the text lines up, not the whole inline block. Siblings have a defined height, which then extends below the text. The parent extends lower to fit all of the children.

So where is the gap coming from? It just so happens that the relative shift puts the .relative div slightly higher than its siblings.

There's something curious about solving the last problem when you applied vertical-align: top to .sibling. You could have actually solved the problem by applying vertical-align: top to .relative too! vertical-align: top shifts the baseline of the relative element to the top, which means that the parent's baseline is back to the top. As a result, the two other siblings no longer get pushed up. Try it yourself and see what happens!